package com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.SmsWnsChargeCategory;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.SmsWnsChargeCategoryDetail;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.req.SmsWnsChargeCategoryDetailReq;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.resp.SmsWnsChargeCategoryDetailResp;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.resp.SmsWnsChargeCategoryResp;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.mapper.SmsWnsChargeCategoryDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.service.SmsWnsChargeCategoryDetailService;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.service.SmsWnsChargeCategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;

/**
 * <p>
 * 收费类别详情表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2024-01-18
 */
@Service
public class SmsWnsChargeCategoryDetailServiceImpl extends ServiceImpl<SmsWnsChargeCategoryDetailMapper, SmsWnsChargeCategoryDetail> implements SmsWnsChargeCategoryDetailService {
    @Resource
    private SmsWnsChargeCategoryService smsWnsChargeCategoryService;

    @Override
    @Transactional
    public ResponseResult addCategoryDetail(SmsWnsChargeCategoryDetailReq categoryDetailReq) {
        if (isNullOrEmpty(categoryDetailReq.getCategoryId(), categoryDetailReq.getName())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        // 有默认价格时必须传入默认价格
        if (!isNullOrEmpty(categoryDetailReq.getHasDefaultPrice())) {
            if (isNullOrEmpty(categoryDetailReq.getDefaultPrice())) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }

        SmsWnsChargeCategory chargeCategory = smsWnsChargeCategoryService.getById(categoryDetailReq.getCategoryId());
        if (chargeCategory == null) {
            return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_CATEGORY_NOT_EXIST);
        }

        // 校验名称是否重复
        if (!isNullOrEmpty(categoryDetailReq.getName())) {
            List<SmsWnsChargeCategoryDetail> sameNameChargeCategoryList = this.list(new LambdaQueryWrapper<SmsWnsChargeCategoryDetail>()
                    .eq(SmsWnsChargeCategoryDetail::getName, categoryDetailReq.getName()));
            if (!sameNameChargeCategoryList.isEmpty()) {
                return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_CATEGORY_NAME_EXIST);
            }
        }

        // 校验顺序是否冲突
        if (!isNullOrEmpty(categoryDetailReq.getSort())) {
            List<SmsWnsChargeCategoryDetail> sameSortChargeCategoryDetailList = this.list(new LambdaQueryWrapper<SmsWnsChargeCategoryDetail>()
                    .eq(SmsWnsChargeCategoryDetail::getCategoryId, categoryDetailReq.getCategoryId())
                    .ge(SmsWnsChargeCategoryDetail::getSort, categoryDetailReq.getSort()));
            if (!sameSortChargeCategoryDetailList.isEmpty()) {
                // 大于当前顺序的每个流程 顺序+1
                for (SmsWnsChargeCategoryDetail categoryDetail : sameSortChargeCategoryDetailList) {
                    categoryDetail.setSort(categoryDetail.getSort() + 1);
                }
                this.updateBatchById(sameSortChargeCategoryDetailList);
            }
        }

        SmsWnsChargeCategoryDetail chargeCategoryDetail = new SmsWnsChargeCategoryDetail();
        BeanUtils.copyProperties(categoryDetailReq, chargeCategoryDetail);
        chargeCategoryDetail.setCategorySort(chargeCategory.getSort());
        if (categoryDetailReq.getSort() == null) {
            int count = this.count(new LambdaQueryWrapper<SmsWnsChargeCategoryDetail>()
                    .eq(SmsWnsChargeCategoryDetail::getCategoryId, categoryDetailReq.getCategoryId()));
            chargeCategoryDetail.setSort(count + 1);
        }
        if (categoryDetailReq.getHasDefaultPrice() == null) {
            chargeCategoryDetail.setHasDefaultPrice(false); // 默认无默认价格
        }
        if (categoryDetailReq.getIsNecessary() == null) {
            chargeCategoryDetail.setIsNecessary(false); // 默认不必须缴纳
        }
        if (categoryDetailReq.getIsModified() == null) {
            chargeCategoryDetail.setIsModified(true); // 默认可修改
        }
        this.save(chargeCategoryDetail);

        return CommonResult.success(chargeCategory.getId());
    }

    @Override
    @Transactional
    public ResponseResult updateCategoryDetail(SmsWnsChargeCategoryDetailReq categoryDetailReq) {
        if (isNullOrEmpty(categoryDetailReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        // 有默认价格时必须传入默认价格
        if (!isNullOrEmpty(categoryDetailReq.getHasDefaultPrice())) {
            if (isNullOrEmpty(categoryDetailReq.getDefaultPrice())) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }

        SmsWnsChargeCategoryDetail categoryDetail = this.getById(categoryDetailReq.getId());
        if (categoryDetail == null) {
            return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_CATEGORY_DETAIL_NOT_EXIST);
        }
        if (!categoryDetail.getIsModified()) {
            return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_CATEGORY_CAN_NOT_UPDATE_OR_DELETE);
        }

        if (!isNullOrEmpty(categoryDetailReq.getCategoryId())) {
            SmsWnsChargeCategory chargeCategory = smsWnsChargeCategoryService.getById(categoryDetailReq.getCategoryId());
            if (chargeCategory == null) {
                return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_CATEGORY_NOT_EXIST);
            }
            categoryDetail.setCategorySort(chargeCategory.getSort());
        }

        // 校验名称是否重复
        if (!isNullOrEmpty(categoryDetailReq.getName())) {
            List<SmsWnsChargeCategoryDetail> sameNameChargeCategoryList = this.list(new LambdaQueryWrapper<SmsWnsChargeCategoryDetail>()
                    .eq(SmsWnsChargeCategoryDetail::getName, categoryDetailReq.getName())
                    .ne(SmsWnsChargeCategoryDetail::getId, categoryDetailReq.getId()));
            if (!sameNameChargeCategoryList.isEmpty()) {
                return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_CATEGORY_NAME_EXIST);
            }
        }

        // 校验顺序是否冲突
        if (!isNullOrEmpty(categoryDetailReq.getSort())) {
            List<SmsWnsChargeCategoryDetail> sameSortChargeCategoryDetailList = this.list(new LambdaQueryWrapper<SmsWnsChargeCategoryDetail>()
                    .eq(SmsWnsChargeCategoryDetail::getCategoryId, categoryDetail.getCategoryId())
                    .eq(SmsWnsChargeCategoryDetail::getSort, categoryDetailReq.getSort())
                    .ne(SmsWnsChargeCategoryDetail::getId, categoryDetailReq.getId()));
            if (!sameSortChargeCategoryDetailList.isEmpty()) {
                // 顺序进行替换
                SmsWnsChargeCategoryDetail conflictCategoryDetail = sameSortChargeCategoryDetailList.get(0);
                conflictCategoryDetail.setSort(categoryDetail.getSort());
                this.updateById(conflictCategoryDetail);
            }
        }

        // 修改当前流程
        BeanUtils.copyProperties(categoryDetailReq, categoryDetail);
        this.updateById(categoryDetail);

        return CommonResult.success();
    }

    @Override
    public ResponseResult listCategoryDetail(Integer pageNum, Integer pageSize, String searchStr) {
        LambdaQueryWrapper<SmsWnsChargeCategoryDetail> queryWrapper = new LambdaQueryWrapper<SmsWnsChargeCategoryDetail>()
                .orderByAsc(SmsWnsChargeCategoryDetail::getSort);

        if (!isNullOrEmpty(searchStr)) {
            StringUtils.deleteWhitespace(searchStr);
            List<SmsWnsChargeCategory> chargeCategoryList = smsWnsChargeCategoryService.list(new LambdaQueryWrapper<SmsWnsChargeCategory>()
                    .and(i -> i.like(SmsWnsChargeCategory::getName, searchStr)
                            .or()
                            .like(SmsWnsChargeCategory::getDescription, searchStr)));
            List<String> chargeCategoryIdList = chargeCategoryList.stream().map(SmsWnsChargeCategory::getId).collect(Collectors.toList());

            queryWrapper.and(i -> i.like(SmsWnsChargeCategoryDetail::getName, searchStr).or()
                    .like(SmsWnsChargeCategoryDetail::getDescription, searchStr).or()
                    .in(!chargeCategoryIdList.isEmpty(), SmsWnsChargeCategoryDetail::getCategoryId, chargeCategoryIdList));
        }

        Page<SmsWnsChargeCategoryDetail> page = new Page<>(pageNum, pageSize);
        this.page(page, queryWrapper);
        List<SmsWnsChargeCategoryDetailResp> categoryDetailRespList = page.getRecords().stream().map(categoryDetail -> {
            SmsWnsChargeCategoryDetailResp categoryDetailResp = new SmsWnsChargeCategoryDetailResp();
            BeanUtils.copyProperties(categoryDetail, categoryDetailResp);

            // 设置类别
            SmsWnsChargeCategory chargeCategory = smsWnsChargeCategoryService.getById(categoryDetail.getCategoryId());
            if (chargeCategory != null) {
                SmsWnsChargeCategoryResp categoryResp = new SmsWnsChargeCategoryResp();
                BeanUtils.copyProperties(chargeCategory, categoryResp);
                categoryDetailResp.setCategoryResp(categoryResp);
            }

            return categoryDetailResp;
        }).collect(Collectors.toList());

        return CommonResult.success(categoryDetailRespList, (int) page.getTotal());
    }

    @Override
    public ResponseResult categoryDetail(String id) {
        SmsWnsChargeCategoryDetail categoryDetail = this.getById(id);
        if (categoryDetail == null) {
            return CommonResult.failed(CommonCodeEnum.WNS_CHARGE_CATEGORY_NOT_EXIST);
        }

        SmsWnsChargeCategoryDetailResp categoryDetailResp = new SmsWnsChargeCategoryDetailResp();
        BeanUtils.copyProperties(categoryDetail, categoryDetailResp);

        // 设置类别
        SmsWnsChargeCategory chargeCategory = smsWnsChargeCategoryService.getById(categoryDetail.getCategoryId());
        SmsWnsChargeCategoryResp categoryResp = new SmsWnsChargeCategoryResp();
        BeanUtils.copyProperties(chargeCategory, categoryResp);
        categoryDetailResp.setCategoryResp(categoryResp);

        return CommonResult.success(categoryDetailResp);
    }
}
